package com.wk.filter;


import com.google.common.util.concurrent.RateLimiter;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 服务限流
 */
@Component
public class ServiceLimitFilter implements Filter {

	//设置令牌生成器生成速率，每秒生成2个，如果是小数，如0.1，则10秒生成1个
	private static final RateLimiter LIMITER = RateLimiter.create(2);

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		//限流的业务逻辑
		if (LIMITER.tryAcquire()) {
			filterChain.doFilter(servletRequest, servletResponse);
		}else {
			servletResponse.setCharacterEncoding("utf-8");
			servletResponse.setContentType("text/html; charset=utf-8");

			PrintWriter writer = servletResponse.getWriter();
			writer.write("被限流");
			writer.close();
		}
	}

	@Override
	public void destroy() {

	}
}
